package com.yint.server;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.yint.core.AbsHandler;
import com.yint.server.state.HandlerState;
import com.yint.server.state.ReadState;

public class Process extends AbsHandler {

	private final SelectionKey sk;
	private final SocketChannel sc;
	private static final int THREAD_COUNTING = 10;
	private static ThreadPoolExecutor exectuor = new ThreadPoolExecutor(THREAD_COUNTING, THREAD_COUNTING, 10,
			TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

	private HandlerState state;

	public Process(SelectionKey sk, SocketChannel sc) {
		this.sk = sk;
		this.sc = sc;
		// 初始状态设定为READING
		state = new ReadState();
		// 设置线程池最大线程数
		exectuor.setMaximumPoolSize(32);
	}

	@Override
	public void close() {
		try {
			sk.cancel();
			sc.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onHandler(SelectionKey selectedKeys) throws IOException {
		System.out.println("Process runing...");
		exectuor.execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					state.handle(Process.this, sk, sc, exectuor);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	@Override
	public void changeState(HandlerState state) {
		this.state = state;
	}
}